package com.example.driptip.ui.home;

import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.PixelFormat;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.driptip.R;
import com.example.driptip.MainActivity;
import com.example.driptip.model.Alarm;
import com.example.driptip.model.Checklist;
import com.example.driptip.util.ChecklistManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeFragment extends Fragment implements AlarmAdapter.AlarmCallback, AlarmAdapter.StopCallback {
    private static final String TAG = "HomeFragment";
    private static final String CHANNEL_ID = "home_alarm_channel";
    private final Map<String, CountDownTimer> activeTimers = new HashMap<>();

    private androidx.appcompat.app.AlertDialog currentAlertDialog;
    private AlarmAdapter alarmAdapter;
    private WindowManager windowManager;
    private View overlayView;

    // 内存状态：true=闹钟运行，false=闹钟结束
    private boolean isAlarmActive = false;

    private int repeatCount = 0; // 记录循环闹钟的弹窗次数

    private long startTimeMillis = 0; // 记录闹钟开始的时间

    private long singleDuration = 0; // 记录单次闹钟的时长（秒）

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            createNotificationChannel();
        } catch (Exception e) {
            showToast("创建通知渠道失败: " + e.getMessage());
        }
    }

    private void showToast(String message) {
        if (getContext() != null) {
            Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Context context = requireContext();
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                try {
                    NotificationChannel channel = new NotificationChannel(
                        CHANNEL_ID,
                        "闹钟提醒",
                        NotificationManager.IMPORTANCE_HIGH
                    );
                    channel.setDescription("首页闹钟响铃提醒");
                    notificationManager.createNotificationChannel(channel);
                } catch (Exception e) {
                    showToast("创建通知渠道失败: " + e.getMessage());
                }
            } else {
                showToast("无法获取通知管理器");
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    @NonNull
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        try {
            View root = inflater.inflate(R.layout.fragment_home, container, false);
            
            RecyclerView recyclerView = root.findViewById(R.id.recycler_alarms);
            if (recyclerView == null) {
                showToast("无法找到闹钟列表视图");
                return root;
            }
            
            // 设置网格布局管理器
            GridLayoutManager layoutManager = new GridLayoutManager(requireContext(), 3);
            layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return position == 0 ? 3 : 1;
                }
            });
            recyclerView.setLayoutManager(layoutManager);
            
            // 初始化 ViewModel
            HomeViewModel homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
            
            // 设置适配器
            alarmAdapter = new AlarmAdapter(requireContext(), homeViewModel.getAlarms().getValue(), this, this);
            recyclerView.setAdapter(alarmAdapter);
            
            // 观察数据变化
            homeViewModel.getAlarms().observe(getViewLifecycleOwner(), alarms -> {
                if (alarmAdapter != null) {
                    alarmAdapter.notifyDataSetChanged();
                } else {
                    showToast("闹钟适配器未初始化");
                }
            });
            
            return root;
        } catch (Exception e) {
            showToast("初始化界面失败: " + e.getMessage());
            return inflater.inflate(R.layout.fragment_home, container, false);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onAlarm(Alarm alarm, boolean isRepeating) {
        // 先停止所有正在运行的闹钟，确保内存状态正确
        for (String alarmId : new ArrayList<>(activeTimers.keySet())) {
            stopTimer(alarmId);
        }
        startTimeMillis = System.currentTimeMillis(); // 记录开始时间
        // 计算单次时长（秒）
        if ("custom".equals(alarm.getType())) {
            singleDuration = (alarm.getHours() * 3600L) + (alarm.getMinutes() * 60L) + alarm.getSeconds();
        } else {
            singleDuration = alarm.getDuration();
        }
        reportAlarmState(true); // 报告闹钟开始
        startTimer(alarm, isRepeating);
    }

    @Override
    public void onStop(String alarmId) {
        stopTimer(alarmId);
        reportAlarmState(false); // 报告闹钟结束
    }

    private void startTimer(Alarm alarm, boolean isRepeating) {
        try {
            // 在循环时，不要调用 stopTimer，直接取消旧的计时器
            CountDownTimer oldTimer = activeTimers.get(alarm.getId());
            if (oldTimer != null) {
                oldTimer.cancel();
                activeTimers.remove(alarm.getId());
            }

            // 计算总时长（毫秒）
            long totalMillis;
            if ("custom".equals(alarm.getType())) {
                totalMillis = ((alarm.getHours() * 3600L) + 
                             (alarm.getMinutes() * 60L) + 
                             alarm.getSeconds()) * 1000L;
            } else {
                totalMillis = alarm.getDuration() * 1000L;
            }

            // 创建并启动计时器
            CountDownTimer timer = new CountDownTimer(totalMillis, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    if (alarmAdapter != null) {
                        alarmAdapter.updateCountdown(alarm.getId(), millisUntilFinished);
                    }
                }

                @Override
                public void onFinish() {
                    playAlarm();
                    if (isRepeating) {
                        startTimeMillis = System.currentTimeMillis(); // 更新开始时间
                        startTimer(alarm, true);
                    } else {
                        stopTimer(alarm.getId());
                        reportAlarmState(false); // 结束时报告
                    }
                }
            };

            activeTimers.put(alarm.getId(), timer);
            alarm.setRunning(true);
            alarm.setRepeating(isRepeating);
            timer.start();
        } catch (Exception e) {
            showToast("启动闹钟失败: " + e.getMessage());
        }
    }

    private void stopTimer(String alarmId) {
        CountDownTimer timer = activeTimers.get(alarmId);
        if (timer != null) {
            timer.cancel();
            activeTimers.remove(alarmId);
            if (alarmAdapter != null) {
                alarmAdapter.stopAlarm(alarmId);
            }
            reportAlarmState(false); // 只要结束就报告
            
            repeatCount = 0; // 清零弹窗次数
            startTimeMillis = 0; // 清零开始时间
            singleDuration = 0; // 清零单次时长
        }
    }

    private void showOverlayWindow(Context context, String title, String message) {
        if (windowManager == null) {
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }

        // 先移除旧的弹窗
        removeOverlayWindow();

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        overlayView = inflater.inflate(R.layout.overlay_layout, null);

        TextView tvTitle = overlayView.findViewById(R.id.tv_title);
        TextView tvMessage = overlayView.findViewById(R.id.tv_message);
        ImageButton closeButton = overlayView.findViewById(R.id.close_button);

        long totalSeconds = singleDuration * (repeatCount + 1); // 使用当前次数+1计算总时长
        repeatCount++; // 增加次数
        tvTitle.setText(title);
        tvMessage.setText(String.format("%s\n总时长：%s，第%d次", message, formatDuration(totalSeconds), repeatCount));

        closeButton.setOnClickListener(v -> removeOverlayWindow());

        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                        WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);

        params.gravity = Gravity.TOP;
        params.y = 100; // 距离顶部100像素

        try {
            windowManager.addView(overlayView, params);
            // 添加自动移除弹窗的计时器
            new CountDownTimer(singleDuration * 1000L - 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    // 不需要做任何事
                }

                @Override
                public void onFinish() {
                    removeOverlayWindow();
                }
            }.start();
        } catch (Exception e) {
            // 如果显示失败，降级到普通对话框
            showFallbackDialog(context, title, message);
        }
    }

    private void removeOverlayWindow() {
        if (overlayView != null && windowManager != null) {
            try {
                windowManager.removeView(overlayView);
            } catch (Exception e) {
            }
            overlayView = null;
        }
    }

    private void showFallbackDialog(Context context, String title, String message) {
        if (currentAlertDialog != null && currentAlertDialog.isShowing()) {
            currentAlertDialog.dismiss();
        }
        long totalSeconds = singleDuration * (repeatCount + 1); // 使用当前次数+1计算总时长
        repeatCount++; // 增加次数
        currentAlertDialog = new androidx.appcompat.app.AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(String.format("%s\n总时长：%s，第%d次", message, formatDuration(totalSeconds), repeatCount))
                .setPositiveButton("完成", null)
                .show();
        // 添加自动移除弹窗的计时器
        new CountDownTimer(singleDuration * 1000L - 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 不需要做任何事
            }

            @Override
            public void onFinish() {
                if (currentAlertDialog != null && currentAlertDialog.isShowing()) {
                    currentAlertDialog.dismiss();
                }
            }
        }.start();
    }

    private void playAlarm() {
        Context context = getContext();
        if (context == null || !isAdded() || isDetached()) {
            showToast("无法播放闹钟：上下文无效");
            return;
        }

        try {
            android.content.SharedPreferences prefs = context.getSharedPreferences("home_settings", Context.MODE_PRIVATE);
            boolean popupEnabled = prefs.getBoolean("popup_enabled", true);
            boolean smsSoundEnabled = prefs.getBoolean("sms_sound_enabled", true);
            boolean vibrationEnabled = prefs.getBoolean("vibration_enabled", true);
            boolean checklistEnabled = ((MainActivity) requireActivity()).isChecklistEnabled();

            // 先移除旧的弹窗
            removeOverlayWindow();

            if (popupEnabled) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(context)) {
                    if (checklistEnabled) {
                        showChecklistOverlay(context);
                    } else {
                        showOverlayWindow(context, "时间到", "计时结束！");
                    }
                } else {
                    if (checklistEnabled) {
                        showChecklistDialog(context);
                    } else {
                        showFallbackDialog(context, "时间到", "计时结束！");
                    }
                }
            }

            if (smsSoundEnabled) {
                Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone ringtone = RingtoneManager.getRingtone(context, notificationUri);
                if (ringtone != null) {
                    ringtone.play();
                } else {
                    showToast("无法播放提示音");
                }
            }

            if (vibrationEnabled) {
                android.os.Vibrator vibrator = (android.os.Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                if (vibrator != null && vibrator.hasVibrator()) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        vibrator.vibrate(android.os.VibrationEffect.createOneShot(500, android.os.VibrationEffect.DEFAULT_AMPLITUDE));
                    } else {
                        vibrator.vibrate(500);
                    }
                } else {
                    showToast("设备不支持振动");
                }
            }
        } catch (Exception e) {
            showToast("播放闹钟失败: " + e.getMessage());
        }
    }

    private String formatDuration(long totalSeconds) {
        long hours = totalSeconds / 3600;
        long minutes = (totalSeconds % 3600) / 60;
        long seconds = totalSeconds % 60;
        
        StringBuilder sb = new StringBuilder();
        if (hours > 0) {
            sb.append(hours).append("小时");
        }
        if (minutes > 0) {
            sb.append(minutes).append("分钟");
        }
        if (seconds > 0 || (hours == 0 && minutes == 0)) {
            sb.append(seconds).append("秒");
        }
        return sb.toString();
    }

    private void showChecklistOverlay(Context context) {
        if (windowManager == null) {
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }

        // 先移除旧的弹窗
        removeOverlayWindow();

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        overlayView = inflater.inflate(R.layout.overlay_checklist, null);

        TextView tvMessage = overlayView.findViewById(R.id.tv_message);
        Button btnConfirm = overlayView.findViewById(R.id.btn_confirm);
        Button btnExtend = overlayView.findViewById(R.id.btn_extend);

        // 每次显示时重新加载清单
        final ChecklistManager checklistManager = new ChecklistManager(context);
        final Checklist checklist = checklistManager.loadChecklist();
        final List<String> items = checklist.getAllItems();

        if (items.isEmpty() || items.get(0).isEmpty()) {
            showOverlayWindow(context, "时间到", "计时结束！");
            return;
        }

        String currentItem = items.get(0);
        String nextItem = items.size() > 1 ? items.get(1) : null;

        if (nextItem != null && !nextItem.isEmpty()) {
            long totalSeconds = singleDuration * (repeatCount + 1); // 使用当前次数+1计算总时长
            repeatCount++; // 增加次数
            tvMessage.setText(String.format("点击完成开始%s，\n点击延长继续%s\n总时长：%s，第%d次", 
                nextItem, currentItem, formatDuration(totalSeconds), repeatCount));
            btnConfirm.setText("完成");
            btnConfirm.setOnClickListener(v -> {
                removeOverlayWindow();
                // 重新加载清单并更新
                Checklist newChecklist = checklistManager.loadChecklist();
                List<String> newItems = newChecklist.getAllItems();
                // 将所有项向前移动一位，直到遇到空项
                for (int i = 0; i < newItems.size() - 1; i++) {
                    String nextItemToMove = newItems.get(i + 1);
                    if (nextItemToMove.isEmpty()) {
                        // 如果下一项为空，将当前项及之后的所有项都设为空
                        for (int j = i; j < newItems.size(); j++) {
                            newItems.set(j, "");
                        }
                        break;
                    }
                    newItems.set(i, nextItemToMove);
                }
                newChecklist.setAllItems(newItems);
                checklistManager.saveChecklist(newChecklist);
                reportAlarmState(false); // 完成时报告
            });
        } else {
            long totalSeconds = singleDuration * (repeatCount + 1); // 使用当前次数+1计算总时长
            repeatCount++; // 增加次数
            tvMessage.setText(String.format("点击完成本轮清单，\n点击延长继续%s\n总时长：%s，第%d次", 
                currentItem, formatDuration(totalSeconds), repeatCount));
            btnConfirm.setText("完成");
            btnConfirm.setOnClickListener(v -> {
                removeOverlayWindow();
                stopTimer("home.custom");
                reportAlarmState(false); // 完成时报告
            });
        }

        btnExtend.setOnClickListener(v -> removeOverlayWindow());

        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                        WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                PixelFormat.TRANSLUCENT);

        params.gravity = Gravity.TOP;
        params.y = 100; // 距离顶部100像素

        try {
            windowManager.addView(overlayView, params);
            // 添加自动移除弹窗的计时器
            new CountDownTimer(singleDuration * 1000L - 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    // 不需要做任何事
                }

                @Override
                public void onFinish() {
                    removeOverlayWindow();
                }
            }.start();
        } catch (Exception e) {
            showChecklistDialog(context);
        }
    }

    private void showChecklistDialog(Context context) {
        // 每次显示时重新加载清单
        final ChecklistManager checklistManager = new ChecklistManager(context);
        final Checklist checklist = checklistManager.loadChecklist();
        final List<String> items = checklist.getAllItems();

        if (items.isEmpty() || items.get(0).isEmpty()) {
            showFallbackDialog(context, "时间到", "计时结束！");
            return;
        }

        String currentItem = items.get(0);
        String nextItem = items.size() > 1 ? items.get(1) : null;

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        if (nextItem != null && !nextItem.isEmpty()) {
            long totalSeconds = singleDuration * (repeatCount + 1); // 使用当前次数+1计算总时长
            repeatCount++; // 增加次数
            builder.setMessage(String.format("点击完成开始%s，\n点击延长继续%s\n总时长：%s，第%d次", 
                nextItem, currentItem, formatDuration(totalSeconds), repeatCount));
            builder.setPositiveButton("完成", (dialog, which) -> {
                dialog.dismiss();  // 先关闭对话框
                // 重新加载清单并更新
                Checklist newChecklist = checklistManager.loadChecklist();
                List<String> newItems = newChecklist.getAllItems();
                // 将所有项向前移动一位，直到遇到空项
                for (int i = 0; i < newItems.size() - 1; i++) {
                    String nextItemToMove = newItems.get(i + 1);
                    if (nextItemToMove.isEmpty()) {
                        // 如果下一项为空，将当前项及之后的所有项都设为空
                        for (int j = i; j < newItems.size(); j++) {
                            newItems.set(j, "");
                        }
                        break;
                    }
                    newItems.set(i, nextItemToMove);
                }
                newChecklist.setAllItems(newItems);
                checklistManager.saveChecklist(newChecklist);
                reportAlarmState(false); // 完成时报告
            });
        } else {
            long totalSeconds = singleDuration * (repeatCount + 1); // 使用当前次数+1计算总时长
            repeatCount++; // 增加次数
            builder.setMessage(String.format("点击完成本轮清单，\n点击延长继续%s\n总时长：%s，第%d次", 
                currentItem, formatDuration(totalSeconds), repeatCount));
            builder.setPositiveButton("完成", (dialog, which) -> {
                dialog.dismiss();  // 先关闭对话框
                stopTimer("home.custom");
                reportAlarmState(false); // 完成时报告
            });
        }
        builder.setNegativeButton("延长", null);
        currentAlertDialog = builder.show();
        // 添加自动移除弹窗的计时器
        new CountDownTimer(singleDuration * 1000L - 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 不需要做任何事
            }

            @Override
            public void onFinish() {
                if (currentAlertDialog != null && currentAlertDialog.isShowing()) {
                    currentAlertDialog.dismiss();
                }
            }
        }.start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            for (CountDownTimer timer : activeTimers.values()) {
                timer.cancel();
            }
            activeTimers.clear();

            // 移除弹窗
            removeOverlayWindow();
        } catch (Exception e) {
            showToast("停止闹钟时出错: " + e.getMessage());
        }
    }

    // 向内存报告闹钟状态
    private void reportAlarmState(boolean isActive) {
        isAlarmActive = isActive;
    }

    // 提供外部查询接口
    public boolean isAlarmRunning() {
        return isAlarmActive;
    }
}